# -*- coding: utf-8 -*-
__author__ = 'liubei'

import base64
from Crypto.Cipher import AES
from Crypto import Random
import hashlib

BS = 16
pad = lambda s: s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
unpad = lambda s: s[0:-ord(s[-1])]
aes_key = '1234567890abcdef'

class AESCipher:
    def __init__(self, key):
        self.key = key

    def encrypt(self, raw):
        raw = pad(str(raw))
        iv = Random.new().read(AES.block_size)
        cipher = AES.new(self.key, AES.MODE_CBC, iv)
        return base64.b64encode(iv + cipher.encrypt(raw))

    def decrypt(self, enc):
        temp = enc
        try:
            enc = base64.b64decode(enc)
            iv = enc[:16]
            cipher = AES.new(self.key, AES.MODE_CBC, iv)
            return unpad(cipher.decrypt(enc[16:]))
        except Exception as err:
            print '======[ aes decrypt error: ' + str(err) + ' ]======'
            return temp

    def decryptWithUnicode(self, enc):
        temp = enc
        try:
            enc = base64.b64decode(enc)
            iv = enc[:16]
            cipher = AES.new(self.key, AES.MODE_CBC, iv)
            return unpad(cipher.decrypt(enc[16:]))
        except Exception as err:
            print '======[ aes decrypt error: ' + str(err) + ' ]======'
            return temp.encode('utf-8')



if __name__ == "__main__":
    aes = AESCipher(aes_key)
    # x1 = aes.encrypt("2015-12-22")
    # x2 = aes.encrypt("2015-12-23")
    x2 = aes.encrypt("1952-04-19")
    print x2
    # x3 = aes.encrypt("")
    # x4 = aes.encrypt("中文")
    # x5 = aes.encrypt(u"中文".encode('utf-8'))
    # print x1
    # print x2
    # print x3
    # print x4
    # print x5
    # y1 = aes.decrypt(x1)
    # y2 = aes.decrypt(x2)
    # y3 = aes.decrypt(x3)
    # y4 = aes.decrypt(x4)
    # y5 = aes.decrypt(x5)
    # y6 = aes.decrypt('2015-12-24')
    # print y1
    # print y2
    # print y3
    # print y4
    # print y5
    # print y6
    # print aes.decrypt('fV7w++BeLaP0/l83BLwiLU74iNnVuAn6rwFdbUhYuAI=')
    # print aes.decrypt('QhFnCkQ9PeCX3cNg7oYpg6/7obCjsRc7MrKXRmHxDLs=')
    # print aes.decrypt('LVTBUqv0AYoqznT/LlURs51gDebFrhrO2Qb6Dmmq+qg=')
    # print aes.decrypt('O4YZ1AFTd3BC5ZoFiSTWQiaz20aLBVIStrPI/ciTG+E=')
    print aes.decrypt('b5n3xWIx9JZV7US0sUEhw5IfGeG3AlqH10/DrdBYetU=')
    # print "beiliubei@gmail.com:0702302613".encode("base64")
    # print hashlib.md5("123456").hexdigest().upper()